package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackStatService;
import com.atguigu.tingshu.model.album.TrackStat;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 声音统计服务实现类
 */
@Slf4j
@Service
public class TrackStatServiceImpl implements TrackStatService {

    @Autowired
    private TrackStatMapper trackStatMapper;

    /**
     * 更新声音统计信息
     *
     * @param albumId  专辑ID
     * @param trackId  声音ID
     * @param statType 统计类型
     * @param count    更新数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTrackStat(Long albumId, Long trackId, String statType, Integer count) {
        log.info("开始更新声音统计 - AlbumId: {}, TrackId: {}, StatType: {}, Count: {}",
                albumId, trackId, statType, count);

        // 查询是否已存在统计记录
        LambdaQueryWrapper<TrackStat> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TrackStat::getTrackId, trackId)
                .eq(TrackStat::getStatType, statType);
        TrackStat trackStat = trackStatMapper.selectOne(queryWrapper);

        if (trackStat == null) {
            // 不存在则新增
            trackStat = new TrackStat();
            trackStat.setTrackId(trackId);
            trackStat.setStatType(statType);
            trackStat.setStatNum(count);
            trackStatMapper.insert(trackStat);
            log.info("新增声音统计记录 - TrackId: {}, StatType: {}, StatNum: {}", trackId, statType, count);
        } else {
            // 已存在则更新（累加）
            trackStat.setStatNum(trackStat.getStatNum() + count);
            trackStatMapper.updateById(trackStat);
            log.info("更新声音统计记录 - TrackId: {}, StatType: {}, NewStatNum: {}",
                    trackId, statType, trackStat.getStatNum());
        }
    }
}
